package net.wanho.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 */
@Configuration
@EnableAsync //  启用异步任务
public class ThreadPoolConfig {

    @Bean
    public Executor taskExecutor() {
        // 定义线程池，使用Spring提供的ThreadPoolTaskExecutor
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(20); // 最大线程数
        executor.setQueueCapacity(50); // 缓冲队列大小
        executor.setKeepAliveSeconds(60); // 线程的空闲时间
        executor.setThreadNamePrefix("AsyncTaskExecutor-"); // 线程前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝处理策略，交由调用方线程运行
        executor.initialize(); // 初始化
        return executor;
    }

}